package com.jason.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

public class UserHbase {

    static Configuration conf=null;
    static Connection conn=null;
    static HBaseAdmin admin =null;

    public static void init () throws IOException {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","hadoop1");
        conf.set("hbase.zookeeper.property.clientPort","2181");
        conn = ConnectionFactory.createConnection(conf);
    }

    public static void destroy() {
        if (admin != null) {
            try {
                admin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void createTable() throws IOException {
        init();
        admin = (HBaseAdmin) conn.getAdmin();
        //创建表描述器
        HTableDescriptor teacher = new HTableDescriptor(TableName.valueOf("user"));
        //设置列族描述器
        teacher.addFamily(new HColumnDescriptor("friends"));
        //执行创建操作
        admin.createTable(teacher);
        System.out.println("user表创建成功！！");
        destroy();
    }

    public static void putData() throws IOException {
        init();
        //获取一个表对象
        Table t = conn.getTable(TableName.valueOf("user"));
        //设定rowkey
        Put put = new Put(Bytes.toBytes("lisi"));
        //列族，列，value
        put.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid1"), Bytes.toBytes("zhangsan"));
        put.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid2"), Bytes.toBytes("wangwu"));
        //put.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid3"), Bytes.toBytes("zhouqi"));
        //执行插入
        t.put(put);
        t.close();
        System.out.println("插入成功！！");
        destroy();
    }

    public static void deleteData() throws IOException {
        init();
        //需要获取一个table对象
        final Table worker = conn.getTable(TableName.valueOf("user"));
        //张三删除李四
        final Delete delete = new Delete(Bytes.toBytes("zhangsan"));
        delete.addColumns(Bytes.toBytes("friends"), Bytes.toBytes("uid1"));
        worker.delete(delete);


        final Delete delete1 = new Delete(Bytes.toBytes("lisi"));
        delete1.addColumns(Bytes.toBytes("friends"), Bytes.toBytes("uid1"));
        worker.delete(delete1);

        //关闭table对象
        worker.close();
        System.out.println("删除数据成功！！");
        destroy();
    }

    public static void main(String[] args) throws IOException {
        deleteData();

    }
}
